package widget.dialog;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.Window;

import java.lang.ref.WeakReference;

import library.logger.Logger;
import widget.R;


/**
 * Created by Mr.Fan on 2017/2/24.
 */

public class ProgressDialog {
    private static WeakReference<AlertDialog> reference;

    public static void show(Context context) {
        show(context, false);
    }

    public static void show(Context context, boolean cancelable) {
        if (!(context instanceof Activity)) {
            return;
        }
        try {
            AlertDialog mProgressDialog = reference != null ? reference.get() : null;
            if (mProgressDialog == null) {
                mProgressDialog = new AlertDialog.Builder(context).create();
            }
            mProgressDialog.setCanceledOnTouchOutside(cancelable);
            mProgressDialog.setCancelable(cancelable);
            if (mProgressDialog.isShowing()) {
                return;
            }
            mProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    reference = null;
                }
            });
            try {
                mProgressDialog.show();
                Window window = mProgressDialog.getWindow();
                window.setBackgroundDrawable(new ColorDrawable());
                window.setContentView(R.layout.dialog_progress);
                window.setGravity(Gravity.CENTER);
            } catch (Exception e) {
                Logger.debug(e);
            }
            reference = new WeakReference<>(mProgressDialog);
        } catch (Exception e) {
            Logger.debug(e);
        }
    }

    public static void dismiss() {
        AlertDialog mProgressDialog = reference != null ? reference.get() : null;
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            reference = null;
        }

    }
}
